#!/bin/bash

# 自动化脚本安装脚本
# 使用方法: ./scripts/install.sh [--service] [--aliases]

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m'

# 显示帮助信息
show_help() {
    echo -e "${BLUE}🚀 自动化脚本安装程序${NC}"
    echo ""
    echo "使用方法:"
    echo "  $0 [选项]"
    echo ""
    echo "选项:"
    echo "  --service          安装系统服务"
    echo "  --aliases          创建shell别名"
    echo "  --all              安装所有功能"
    echo "  --help             显示此帮助信息"
    echo ""
    echo "示例:"
    echo "  $0 --all                    # 安装所有功能"
    echo "  $0 --service                # 仅安装系统服务"
    echo "  $0 --aliases                # 仅创建别名"
    echo ""
}

# 检查依赖
check_dependencies() {
    echo -e "${BLUE}🔍 检查依赖...${NC}"
    
    local missing_deps=()
    
    # 检查jq
    if ! command -v jq &> /dev/null; then
        missing_deps+=("jq")
    fi
    
    # 检查git
    if ! command -v git &> /dev/null; then
        missing_deps+=("git")
    fi
    
    if [ ${#missing_deps[@]} -gt 0 ]; then
        echo -e "${RED}❌ 缺少依赖: ${missing_deps[*]}${NC}"
        echo ""
        echo "请安装缺少的依赖:"
        echo ""
        echo "Ubuntu/Debian:"
        echo "  sudo apt-get update"
        echo "  sudo apt-get install ${missing_deps[*]}"
        echo ""
        echo "CentOS/RHEL:"
        echo "  sudo yum install ${missing_deps[*]}"
        echo ""
        echo "macOS:"
        echo "  brew install ${missing_deps[*]}"
        echo ""
        exit 1
    fi
    
    echo -e "${GREEN}✓ 所有依赖已满足${NC}"
    echo ""
}

# 设置脚本权限
set_permissions() {
    echo -e "${BLUE}🔧 设置脚本权限...${NC}"
    
    chmod +x scripts/*.sh
    
    echo -e "${GREEN}✓ 脚本权限设置完成${NC}"
    echo ""
}

# 创建目录
create_directories() {
    echo -e "${BLUE}📁 创建必要目录...${NC}"
    
    mkdir -p scripts/log-monitor-data
    mkdir -p scripts/log-monitor-reports
    
    echo -e "${GREEN}✓ 目录创建完成${NC}"
    echo ""
}

# 安装系统服务
install_service() {
    echo -e "${BLUE}🔧 安装系统服务...${NC}"
    
    local service_file="scripts/log-monitor.service"
    local systemd_dir="/etc/systemd/system"
    local service_name="log-monitor.service"
    
    if [ ! -f "$service_file" ]; then
        echo -e "${RED}❌ 服务文件不存在: $service_file${NC}"
        return 1
    fi
    
    # 复制服务文件
    sudo cp "$service_file" "$systemd_dir/"
    
    # 重新加载systemd
    sudo systemctl daemon-reload
    
    # 启用服务
    sudo systemctl enable "$service_name"
    
    echo -e "${GREEN}✓ 系统服务安装完成${NC}"
    echo -e "${CYAN}服务状态:${NC}"
    echo -e "  启动: sudo systemctl start $service_name"
    echo -e "  停止: sudo systemctl stop $service_name"
    echo -e "  状态: sudo systemctl status $service_name"
    echo -e "  日志: sudo journalctl -u $service_name -f"
    echo ""
}

# 创建shell别名
create_aliases() {
    echo -e "${BLUE}🔗 创建shell别名...${NC}"
    
    local shell_rc=""
    local current_shell=$(basename "$SHELL")
    
    case "$current_shell" in
        "bash")
            shell_rc="$HOME/.bashrc"
            ;;
        "zsh")
            shell_rc="$HOME/.zshrc"
            ;;
        *)
            echo -e "${YELLOW}⚠️  未知的shell类型: $current_shell${NC}"
            echo -e "${CYAN}请手动添加以下别名到您的shell配置文件中:${NC}"
            echo ""
            show_aliases
            return 0
            ;;
    esac
    
    # 检查是否已经存在别名
    if grep -q "alias aicommit" "$shell_rc" 2>/dev/null; then
        echo -e "${YELLOW}⚠️  别名已存在，跳过创建${NC}"
        return 0
    fi
    
    # 添加别名
    echo "" >> "$shell_rc"
    echo "# 自动化脚本别名" >> "$shell_rc"
    echo "# AI代码commit" >> "$shell_rc"
    echo "alias aicommit='./scripts/quick-commit.sh'" >> "$shell_rc"
    echo "alias aicommit-full='./scripts/auto-commit.sh'" >> "$shell_rc"
    echo "" >> "$shell_rc"
    echo "# 插件分支管理" >> "$shell_rc"
    echo "alias plugin-list='./scripts/plugin-branch-switcher.sh --list'" >> "$shell_rc"
    echo "alias plugin-status='./scripts/plugin-branch-switcher.sh --status'" >> "$shell_rc"
    echo "alias plugin-switch='./scripts/plugin-branch-switcher.sh'" >> "$shell_rc"
    echo "" >> "$shell_rc"
    echo "# 日志监控" >> "$shell_rc"
    echo "alias log-scan='./scripts/log-monitor.sh --scan'" >> "$shell_rc"
    echo "alias log-report='./scripts/log-monitor.sh --report'" >> "$shell_rc"
    echo "alias log-daemon='./scripts/log-monitor.sh --daemon'" >> "$shell_rc"
    echo "" >> "$shell_rc"
    
    echo -e "${GREEN}✓ 别名已添加到 $shell_rc${NC}"
    echo -e "${CYAN}请运行以下命令重新加载配置:${NC}"
    echo -e "  source $shell_rc"
    echo ""
}

# 显示别名信息
show_aliases() {
    echo -e "${CYAN}可用的别名:${NC}"
    echo ""
    echo "# AI代码commit"
    echo "alias aicommit='./scripts/quick-commit.sh'"
    echo "alias aicommit-full='./scripts/auto-commit.sh'"
    echo ""
    echo "# 插件分支管理"
    echo "alias plugin-list='./scripts/plugin-branch-switcher.sh --list'"
    echo "alias plugin-status='./scripts/plugin-branch-switcher.sh --status'"
    echo "alias plugin-switch='./scripts/plugin-branch-switcher.sh'"
    echo ""
    echo "# 日志监控"
    echo "alias log-scan='./scripts/log-monitor.sh --scan'"
    echo "alias log-report='./scripts/log-monitor.sh --report'"
    echo "alias log-daemon='./scripts/log-monitor.sh --daemon'"
    echo ""
}

# 验证安装
verify_installation() {
    echo -e "${BLUE}✅ 验证安装...${NC}"
    
    local errors=0
    
    # 检查脚本文件
    local scripts=("auto-commit.sh" "quick-commit.sh" "plugin-branch-switcher.sh" "log-monitor.sh")
    for script in "${scripts[@]}"; do
        if [ -f "scripts/$script" ]; then
            echo -e "${GREEN}✓ $script${NC}"
        else
            echo -e "${RED}❌ $script 不存在${NC}"
            ((errors++))
        fi
    done
    
    # 检查目录
    local dirs=("scripts/log-monitor-data" "scripts/log-monitor-reports")
    for dir in "${dirs[@]}"; do
        if [ -d "$dir" ]; then
            echo -e "${GREEN}✓ $dir${NC}"
        else
            echo -e "${RED}❌ $dir 不存在${NC}"
            ((errors++))
        fi
    done
    
    # 检查配置文件
    if [ -f "scripts/log-monitor.conf" ]; then
        echo -e "${GREEN}✓ log-monitor.conf${NC}"
    else
        echo -e "${YELLOW}⚠️  log-monitor.conf 不存在 (将在首次运行时创建)${NC}"
    fi
    
    if [ -f "scripts/plugins-list.txt" ]; then
        echo -e "${GREEN}✓ plugins-list.txt${NC}"
    else
        echo -e "${YELLOW}⚠️  plugins-list.txt 不存在${NC}"
    fi
    
    echo ""
    
    if [ $errors -eq 0 ]; then
        echo -e "${GREEN}🎉 安装验证成功！${NC}"
    else
        echo -e "${RED}❌ 安装验证失败，有 $errors 个错误${NC}"
        return 1
    fi
}

# 显示使用说明
show_usage_info() {
    echo -e "${BLUE}📖 使用说明${NC}"
    echo "========================================"
    echo ""
    echo -e "${CYAN}快速开始:${NC}"
    echo "1. AI代码commit:"
    echo "   aicommit 'feat: 新增功能'"
    echo ""
    echo "2. 插件分支管理:"
    echo "   plugin-status                    # 查看插件状态"
    echo "   plugin-switch feature/new --all  # 切换所有插件分支"
    echo ""
    echo "3. 日志监控:"
    echo "   log-scan                         # 扫描日志"
    echo "   log-report                       # 生成报告"
    echo ""
    echo -e "${CYAN}详细文档:${NC}"
    echo "   cat scripts/README.md"
    echo ""
}

# 主函数
main() {
    local install_service_flag="false"
    local install_aliases_flag="false"
    
    # 解析参数
    while [[ $# -gt 0 ]]; do
        case $1 in
            -h|--help)
                show_help
                exit 0
                ;;
            --service)
                install_service_flag="true"
                shift
                ;;
            --aliases)
                install_aliases_flag="true"
                shift
                ;;
            --all)
                install_service_flag="true"
                install_aliases_flag="true"
                shift
                ;;
            -*)
                echo -e "${RED}错误: 未知参数 $1${NC}"
                show_help
                exit 1
                ;;
            *)
                echo -e "${RED}错误: 未知参数 $1${NC}"
                show_help
                exit 1
                ;;
        esac
    done
    
    echo -e "${BLUE}🚀 自动化脚本安装程序${NC}"
    echo "========================================"
    echo ""
    
    # 检查是否在项目根目录
    if [ ! -f "scripts/README.md" ]; then
        echo -e "${RED}❌ 请在项目根目录运行此脚本${NC}"
        exit 1
    fi
    
    # 执行安装步骤
    check_dependencies
    set_permissions
    create_directories
    
    if [ "$install_service_flag" = "true" ]; then
        install_service
    fi
    
    if [ "$install_aliases_flag" = "true" ]; then
        create_aliases
    fi
    
    verify_installation
    show_usage_info
    
    echo -e "${GREEN}🎉 安装完成！${NC}"
    echo ""
    echo -e "${CYAN}下一步:${NC}"
    echo "1. 如果创建了别名，请重新加载shell配置"
    echo "2. 查看详细文档: cat scripts/README.md"
    echo "3. 开始使用自动化工具"
    echo ""
}

# 执行主函数
main "$@" 